package com.web.user.member.filter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.mysteel.util.ObjectUtils;

public class MemberAuthInterceptor implements HandlerInterceptor
{
	public static final String SESSION_CONTEXT_NAME = "context";
	
	public static final String COOKIE_LASTLOGIN_ADMINID = "_last_loginaid";
	
	public static final String COOKIE_LOGIN_DOMAIN = "kongjianxiu.xicp.net";
	//public static final String COOKIE_LOGIN_DOMAIN = "127.0.0.1";

	public static final String COOKIE_LOGIN_TOKEN = "_login_token";
	
	public static final String COOKIE_USERID_TOKEN = "_login_userid";  //�û�id��COOKIE
	
	public static final String COOKIE_USERNAME_TOKEN = "_login_name";  //�û����Ƶ�COOKIE
	
	public static final String COOKIE_MEMBERID_TOKEN = "_login_name_memberid";  //��Աid��COOKIE
	
	public static final String COOKIE_MEMBER_NAME_TOKEN = "_login_name_membername";  //��Ա���Ƶ�COOKIE
	
	public static final String COOKIE_USER_REALNAME_TOKEN = "_login_name_userrealname";  //�û���ʵ���Ƶ�COOKIE
	
	public static final String MEMBER_SESSION = "MEMBER_SESSION"; // ��Ա��ϢSession
	
	
	
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
		
		/*	LoginContext context = (LoginContext) request.getSession().getAttribute(MEMBER_SESSION);

			if (context == null)
			{
				String key = ServletUtils.getCookieValue(request, COOKIE_LOGIN_TOKEN);

				if (!StringUtils.isEmpty(key))
				{
					context = cacheService.get(key);
				}

				if (context == null)
				{
					response.sendRedirect("/member/viewLogin.jsp");
					return false;
				}
				request.getSession().setAttribute(MEMBER_SESSION, context);
			}
			request.setAttribute("context", context);
			
			if (request.getParameter("page") == null)
			{
				request.setAttribute("page", 0);
			}
			request.setAttribute("refererURL", request.getHeader("REFERER"));
			return true;
		*/
		
		Cookie[] ck = request.getCookies ();
		
		if(ObjectUtils.isEmpty (ck))
		{
			response.sendRedirect ("/member/login.html");
		}else
		{
			for(Cookie cookie:ck)
			{
				if(cookie.getName ().equals ("member_id"))
				{
					request.setAttribute ("memberId" ,cookie.getValue ());
				}
			}
		}
		
		return true;
	}

}
